package com.dsf.blog.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.dsf.blog.dto.DetailedBlog;
import com.dsf.blog.dto.FirstPageBlog;
import com.dsf.blog.dto.RecommendBlog;
import com.dsf.blog.po.Comment;
import com.dsf.blog.po.Tag;
import com.dsf.blog.po.Type;
import com.dsf.blog.service.BlogService;
import com.dsf.blog.service.CommentService;
import com.dsf.blog.service.TagService;
import com.dsf.blog.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class IndexController {
    @Autowired
    BlogService blogService;

    @Autowired
    TagService tagService;

    @Autowired
    TypeService typeService;

    @Autowired
    private CommentService commentService;

    @GetMapping("/")
    public String toIndex(Model model, @RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum){
        PageHelper.startPage(pageNum,6);
        List<FirstPageBlog> allFirstPageBlog = blogService.getAllFirstPageBlog();
        System.out.println("allFirstPageBlog：----》"+allFirstPageBlog);
//        List<Type> allType = typeService.getAllType();
        List<Type> types=typeService.findTypeListBefore(7);
        List<Tag> allTag = tagService.getAllTag();
        System.out.println("alltag:"+allTag);
        List<RecommendBlog> recommendedBlog = blogService.getRecommendedBlog();
        PageInfo<FirstPageBlog> pageInfo = new PageInfo<>(allFirstPageBlog);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("tags", allTag);
        model.addAttribute("types", types);
        model.addAttribute("recommendedBlogs", recommendedBlog);
        return "index";
    }

    @PostMapping("/search")
    public String toSearch(@RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,
                           Model model,@RequestParam String query){
        PageHelper.startPage(pageNum, 100);
        List<FirstPageBlog> searchBlog = blogService.getSearchBlog(query);
        PageInfo<FirstPageBlog> pageInfo = new PageInfo<>(searchBlog);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("query", query);
        return "search";
    }

    @GetMapping("/blog/{id}")
    public String toBlog(@PathVariable Long id,Model model){
        DetailedBlog detailedBlog = blogService.getDetailedBlog(id);
        List<Comment> comments = commentService.listCommentByBlogId(id);
        model.addAttribute("comments", comments);
        model.addAttribute("blog", detailedBlog);
        return "blog";
    }
}
